package com.kooison.trafficMonitor;

import java.util.ArrayList;
import java.util.Date;
import java.util.Properties;

import javax.jdo.PersistenceManager;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;

import com.kooison.crawler.xml.impl.TdCrawler;
import com.kooison.crawler.xml.jaxb.model.td.Area;
import com.kooison.crawler.xml.jaxb.model.td.Dot;
import com.kooison.crawler.xml.jaxb.model.td.TrafficInfo;
import com.kooison.database.gae.PMF;
import com.kooison.trafficMonitor.database.Camera;
import com.kooison.util.properties.PropertyLoader;

public class CacheController extends AbstractController {

	private static TdCrawler crawler;

	public TdCrawler getCrawler() {
		return crawler;
	}

	public void setCrawler(TdCrawler crawler) {
		CacheController.crawler = crawler;
	}

	private static Properties props;

	@Override
	protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		Date time1 = new Date();
		if (props == null)
			props = PropertyLoader.loadProperties("location.properties");

		crawler.setAreas(new String[] { "" });
		crawler.setPath("http://www.news.gov.hk/common/feedin/traffic/publish_area/trafficHK.xml");
		crawler.setMarshallType(TrafficInfo.class);

		TrafficInfo ti = (TrafficInfo) crawler.getResult();
		logger.info(ti.toString());

		PersistenceManager pm = PMF.get().getPersistenceManager();
		ArrayList<Camera> l = new ArrayList<Camera>();
		for (Area a : ti.getArea()) {
			for (Dot d : a.getDot()) {
				String latlng = props.getProperty("latlng." + d.getDotID());
				if (latlng != null && latlng.trim().length() > 0) {
					Camera c = new Camera(d.getDotID(), latlng, d.getDotURL(), new Date());
					l.add(c);
				}
			}
		}
		pm.makePersistentAll(l);
		pm.close();
		Date time2 = new Date();

		long timeDiff = time2.getTime() - time1.getTime();
		
		response.setContentType("text/html");
		response.getWriter().println(l.size() + " points were updated in " + timeDiff  + "ms.<br>");
		response.getWriter().println(new Date());
		
		return null;
	}
}
